import 'dart:math';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xvideos/assets_tool/images.dart';
import 'package:xvideos/tools_base/widget/net_image_widget.dart';

import '../../hj_model/splash/ads_model.dart';
import '../../routers/jump_router.dart';
import '../../tools_base/banner/ads_banner_widget.dart';
import '../../tools_base/debug_log.dart';

class ApplicationCenterDialog extends Dialog {
  final List<AdsInfoModel>? appList;
  final List<AdsInfoModel>? adsList;
  final VoidCallback? callback;

  const ApplicationCenterDialog({Key? key, this.appList, this.callback, this.adsList}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Material(
        color: Colors.black.withOpacity(0.6),
        child: ApplicationCenter(
          appList: appList,
          adsList: adsList,
          callback: callback,
        ));
  }
}

class ApplicationCenter extends StatefulWidget {
  final List<AdsInfoModel>? appList;
  final List<AdsInfoModel>? adsList;
  final VoidCallback? callback;

  const ApplicationCenter({Key? key, this.appList, this.callback, this.adsList}) : super(key: key);

  @override
  State<ApplicationCenter> createState() => _ApplicationCenterState();
}

class _ApplicationCenterState extends State<ApplicationCenter> {
  bool _showClose = false;
  GlobalKey _globalKey = GlobalKey();

  double? gridViewHeight;
  bool get hasGridHeight => (gridViewHeight ?? 0) > 0;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      getGridViewHeightValue();
    });
    Future.delayed(const Duration(milliseconds: 1000), () {
      _showClose = true;
      if (mounted) {
        setState(() {});
      }
    });
  }

  void getGridViewHeightValue() {
    try {
      RenderBox? renderBox = _globalKey.currentContext?.findRenderObject() as RenderBox?;
      gridViewHeight = renderBox?.size.height ?? 0;
      if ((gridViewHeight ?? 0) > 0) {
        setState(() {});
      }
    } catch (e) {
      debugLog(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        if (widget.adsList?.isNotEmpty == true)
          Container(
            margin: const EdgeInsets.only(bottom: 24),
            child: AdsBannerWidget(
              widget.adsList,
              width: 329,
              height: 88,
              autoPlayDuration: 5000,
              onItemClick: (index) {
                var ad = widget.adsList![index];
                pushToPageByLink(ad.href, id: ad.id);
              },
            ),
          ),
        SizedBox(
          key: _globalKey,
          height: hasGridHeight ? (gridViewHeight! + 25) : null,
          child: GridView.builder(
            padding: const EdgeInsets.symmetric(horizontal: 28),
            itemCount: hasGridHeight ? widget.appList!.length : min(16, widget.appList!.length),
            shrinkWrap: hasGridHeight ? false : true,
            physics: hasGridHeight ? ClampingScrollPhysics() : NeverScrollableScrollPhysics(),
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 4,
              crossAxisSpacing: 12,
              mainAxisSpacing: 16,
              childAspectRatio: 68 / 93,
            ),
            itemBuilder: (context, index) {
              AdsInfoModel app = widget.appList![index];
              return GestureDetector(
                onTap: () {
                  pushToPageByLink(app.href, id: app.id);
                },
                child: Column(
                  children: [
                    Expanded(
                      child: AspectRatio(
                        aspectRatio: 1,
                        child: NetworkImageLoader(
                          width: double.infinity,
                          height: double.infinity,
                          imageUrl: app.cover ?? "",
                          borderRadius: 12,
                        ),
                      ),
                    ),
                    const SizedBox(height: 6),
                    Text(
                      app.title ?? "",
                      maxLines: 1,
                      //overflow: TextOverflow.ellipsis,
                      style: const TextStyle(
                        fontSize: 11,
                        color: Colors.white,
                      ),
                    ),
                  ],
                ),
              );
            },
          ),
        ),
        const SizedBox(height: 32),
        _showClose
            ? GestureDetector(
                onTap: () => Get.back(),
                child: Image.asset(
                  "close_button.png".commonImgPath,
                  width: 32,
                  height: 32,
                ),
              )
            : const SizedBox(
                height: 32,
              ),
      ],
    );
  }
}
